<?php

/**
 * This is the model class for table "{{company}}".
 *
 * The followings are the available columns in table '{{company}}':
 * @property integer $zm_id
 * @property integer $zct_id
 * @property string $zc_name
 * @property string $zc_en_name
 * @property string $zc_entity_num
 * @property string $zc_domain
 * @property string $zc_sub_domain
 * @property string $zc_corpnname
 * @property string $zc_seotitle
 * @property string $zc_seokey
 * @property string $zc_seodesc
 * @property integer $zar_id
 * @property string $zc_adr
 * @property integer $zc_zip
 * @property integer $zca_id
 * @property string $zc_content
 * @property string $zc_business_model
 * @property string $zc_business_brand
 * @property string $zc_main_pro
 * @property string $zc_main_exp
 * @property string $zc_main_mkt
 * @property string $zc_main_accounts
 * @property string $zc_year_turnover
 * @property string $zc_lnsize
 * @property integer $zc_found_date
 * @property integer $zc_customize
 * @property string $zc_logo
 * @property string $zc_com_pic
 * @property string $zc_banner
 * @property integer $zc_status
 * @property integer $zc_commend
 * @property integer $zc_hits
 * @property integer $zc_write
 * @property integer $inputtime
 * @property integer $updatetime
 */
class Company extends CActiveRecord
{
	//店铺首页头部自定义编辑区
	public $block_head;
	
	//店铺首页右侧自定义编辑区
	public $block_right;
	
	//二级域名
	public $domain;
	
	//行业分类，一级行业分类，用于查询
	public $category_top;
	
	//店铺状态，用于查询
	public $shop_status;
	
	//用户名或店铺名
	public $user_company_name;
	
	//店铺评论统计
	public $comment;
	
	//排序;1创建时间倒序，2销量倒序
	public $list_order = 1;
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Company the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{company}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('zca_id,zc_name,zar_id,zc_zip','required'),
 			array('zar_id, zc_zip, zca_id, zc_found_date, zc_customize,zc_write,category_top,shop_status,list_order','numerical', 'integerOnly'=>true),
			array('zc_zip', 'length', 'max'=>6,'min'=>6),//邮编
			array('zc_deposit', 'numerical'),
			array('zc_name, zc_entity_num, zc_year_turnover, zc_lnsize,zc_cmp_type,zc_reg_capital,zc_logo,zc_banner,zc_com_pic', 'length', 'max'=>100),
 			array('zc_en_name, zc_domain, zc_adr, zc_main_pro, zc_main_mkt, zc_main_accounts,zc_seodesc', 'length', 'max'=>255),
 			array('zc_corpnname,zc_sub_domain', 'length', 'max'=>20),
 			array('zc_business_model, zc_business_brand, zc_main_exp', 'length', 'max'=>50),
 			array('zc_content,block_head,block_right', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('zm_id, zct_id, zc_name, zc_en_name, zc_entity_num, zc_domain, zc_sub_domain, zc_corpnname, zc_seotitle, zc_seokey, zc_seodesc, zar_id, zc_adr, zc_zip, zca_id, zc_content, zc_business_model, zc_business_brand, zc_main_pro, zc_main_exp, zc_main_mkt, zc_main_accounts, zc_year_turnover, zc_lnsize, zc_found_date, zc_customize, zc_logo, zc_com_pic, zc_banner, zc_status, zc_commend, zc_hits, zc_write, inputtime, updatetime', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
				'member'=>array(self::BELONGS_TO,'Member','zm_id'),
				'services'=>array(self::HAS_MANY,'CmpServices','zm_id'),//客服信息
				'contact'=>array(self::HAS_MANY,'CmpContact','zm_id','order'=>'zcc_default DESC'),
				'favCount'=>array(self::STAT, 'MemFav', 'zp_id','condition'=>'zmf_type=2'),
				'category'=>array(self::BELONGS_TO,'Category','zca_id'),
				'template'=>array(self::BELONGS_TO,'CmpTemplates','zct_id'),//模板
				'category'=>array(self::BELONGS_TO,'Category','zca_id'),//行业分类
				'productCount'=>array(self::STAT, 'Product', 'zm_id' , 'condition'=>'zp_status=2 and zp_state in (1,2)'),//商家产品数
				'orderCount'=>array(self::STAT, 'OrdProduct', 'zm_id','select'=>'SUM(zop_nums)','condition'=>'zop_status=0','order'=>' SUM(zop_nums) DESC '),//商家销量
			//	'comment'=>array(self::HAS_ONE,'OrdComment','zm_id','on'=>'zoc_type=2','select'=>'AVG(zoc_product) as avg_product,AVG(zoc_service) as avg_service, AVG(zoc_express) as avg_express',)
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'zm_id' => '会员ID',
			'zct_id' => '模板ID',
			'zc_name' => '公司名称',
			'zc_en_name' => '公司英文名',
			'zc_entity_num' => '实体店铺号',
			'zc_domain' => '顶级域名',
			'zc_sub_domain' => '二级域名',
			'zc_corpnname' => '法人代表',
			'zc_seotitle' => 'SEO标题',
			'zc_seokey' => 'SEO关键词',
			'zc_seodesc' => 'SEO描述',
			'zar_id' => '地域ID',
			'zc_adr' => '公司地址',
			'zc_zip' => '邮编',
			'zca_id' => '行业分类',
			'zc_cmp_type' => '公司类型',
			'zc_reg_capital' => '注册资金',
			'zc_deposit'=>'保障金',
			'zc_content' => '备注',
			'zc_business_model' => '经营模式',
			'zc_business_brand' => '经营品牌',
			'zc_main_pro' => '主营产品',
			'zc_main_exp' => '主营方向',
			'zc_main_mkt' => '主要市场',
			'zc_main_accounts' => '主要客户群',
			'zc_year_turnover' => '年营业额',
			'zc_lnsize' => '公司人数',
			'zc_found_date' => '成立时间',
			'zc_customize' => '否提供加工',//1否2是
			'zc_logo' => '公司LOGO',
			'zc_com_pic' => '公司形象图',
			'zc_banner' => '公司BANNER图',
			'zc_status' => '状态',//1未审2已审',
			'zc_commend' => '是否推荐',//1否2是
			'zc_hits' => '点击数',
			'zc_write' => '二级域名可写状态',//1可写2不可写
			'inputtime' => '创建时间',
			'updatetime' => '更新时间',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('zm_id',$this->zm_id);
		$criteria->compare('zct_id',$this->zct_id);
		$criteria->compare('zc_name',$this->zc_name,true);
		$criteria->compare('zc_en_name',$this->zc_en_name,true);
		$criteria->compare('zc_entity_num',$this->zc_entity_num,true);
		$criteria->compare('zc_domain',$this->zc_domain,true);
		$criteria->compare('zc_sub_domain',$this->zc_sub_domain,true);
		$criteria->compare('zc_corpnname',$this->zc_corpnname,true);
		$criteria->compare('zc_seotitle',$this->zc_seotitle,true);
		$criteria->compare('zc_seokey',$this->zc_seokey,true);
		$criteria->compare('zc_seodesc',$this->zc_seodesc,true);
		$criteria->compare('zar_id',$this->zar_id);
		$criteria->compare('zc_adr',$this->zc_adr,true);
		$criteria->compare('zc_zip',$this->zc_zip);
		$criteria->compare('zc_cmp_type',$this->zc_cmp_type);
		$criteria->compare('zc_reg_capital',$this->zc_reg_capital);
		$criteria->compare('zc_deposit',$this->zc_deposit);
		$criteria->compare('zc_content',$this->zc_content,true);
		$criteria->compare('zc_business_model',$this->zc_business_model,true);
		$criteria->compare('zc_business_brand',$this->zc_business_brand,true);
		$criteria->compare('zc_main_pro',$this->zc_main_pro,true);
		$criteria->compare('zc_main_exp',$this->zc_main_exp,true);
		$criteria->compare('zc_main_mkt',$this->zc_main_mkt,true);
		$criteria->compare('zc_main_accounts',$this->zc_main_accounts,true);
		$criteria->compare('zc_year_turnover',$this->zc_year_turnover,true);
		$criteria->compare('zc_lnsize',$this->zc_lnsize,true);
		$criteria->compare('zc_deposit',$this->zc_deposit);
		$criteria->compare('zc_found_date',$this->zc_found_date);
		$criteria->compare('zc_customize',$this->zc_customize);
		$criteria->compare('zc_logo',$this->zc_logo,true);
		$criteria->compare('zc_com_pic',$this->zc_com_pic,true);
		$criteria->compare('zc_banner',$this->zc_banner,true);
		
		$criteria->compare('zc_commend',$this->zc_commend);
		$criteria->compare('zc_hits',$this->zc_hits);
		$criteria->compare('zc_write',$this->zc_write);
		$criteria->compare('inputtime',$this->inputtime);
		$criteria->compare('updatetime',$this->updatetime);
		$criteria->join = '';
		//根据一级行业分类查找商铺
		if(!empty($this->category_top)){
			$catetop = Category::model()->findByPk($this->category_top);
			$criteria->join .= ' LEFT JOIN {{category}} cat ON cat.zca_id=t.zca_id';
			$criteria->addCondition(" (t.zca_id={$this->category_top} OR (t.zca_id IN ({$catetop->zca_arrchildid}))) ");
		}else{
			$criteria->compare('zca_id',$this->zca_id);
		}
		
		//根据店铺状态查询
		if(!empty($this->shop_status)){
			if($this->shop_status==1){
				$criteria->compare('zc_status',1);
			}elseif($this->shop_status==2){
				$criteria->compare('zc_status',2);
				$criteria->compare('zc_deposit_status',1);
			}elseif($this->shop_status==3){
				$criteria->compare('zc_status',2);
				$criteria->compare('zc_deposit_status',2);
			}elseif($this->shop_status==4){
				$criteria->compare('zc_status',3);
			}
		}else{
			$criteria->compare('zc_status',$this->zc_status);//状态:1未审2已审3锁定
			$criteria->compare('zc_deposit_status',$this->zc_deposit_status);//保证金审核状态
		}
		//排序
		if($this->list_order == 1){
			//时间倒序，默认
			$criteria->order = " inputtime DESC ";
		}elseif($this->list_order == 2){
			//销量倒序
			$criteria->join .= ' LEFT JOIN {{ord_product}} op ON op.zm_id=t.zm_id';
			$criteria->select = "t.*,SUM(op.zop_nums) as opsum ";
			$criteria->group = "zm_id";
			$criteria->order = " opsum DESC ";
		}
		
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
   /*
    * 根据产品id查找商家单条记录
    * @params $productid 产品id
    **/
	public function getComByProid($productid){
		$memid = Product::model()->find('zp_id=\''.$productid.'\'')->zm_id;
		return $this->model()->find('zm_id=\''.$memid.'\'');
	}
	/**
	 * 保存数据前的操作
	 * 
	 */
	protected function beforeSave(){
		if(parent::beforeSave()){
			if($this->isNewRecord){
				//会员ID
				$this->zm_id = Yii::app()->user->userid;
				//默认模板
				$this->zct_id = '1';
				//SEO标题
				$this->zc_seotitle = '';
				//SEO关键词
				$this->zc_seokey = '';
				//SEO描述
				$this->zc_seodesc = '';
				//状态
				$this->zc_status = '1';
				//是否推荐 为否
				$this->zc_commend = '1';
				//二级域名可写状态
				$this->zc_write = '1';
				//创建时间
				$this->inputtime = time();
				return true;
			}else{
				$this->updatetime = time();
				return true;
			}
		}else{
			return false;
		}
	}
	
	/**
	 *获取登录会员的商家ID 
	 */
	public function getCmpUserId(){
		$userid = Yii::app()->user->getid();
		
		if(empty($userid)){
			return 1;
		}
		
		//如果是后台操作，返回1默认商家ID
		if(isset(Yii::app()->user->manage)){
			return 1;
		}
		
		//如果是子账号，则返回对应商家ID
		$userid = explode(':',$userid);
		if(count($userid)==2){
			return Yii::app()->user->cmpid;
		}else{
			if(empty(Yii::app()->user->comgroup)){
				return '';
			}else{
				return $userid[0];
			}
		}
	}
	/**
	 *获取登录会员的商家	会员名
	 */
	public function getCmpUserName(){
		$userid = Yii::app()->user->getid();
		if(is_int($userid)){
			return Yii::app()->user->getName();
		}else{
			//如果是子账号，则返回对应商家ID
			$userid = explode(':',$userid);
			if(count($userid)==2){
				return $userid[0];
			}else{
				return Yii::app()->user->getName();
			}
		}
	}
	/**
	 *根据会员id获取公司信息、联系信息、客服信息
	 *return array
	 */
	public function getCompanyByMemberId($memberid){
		$record = $this->with('services','contact','favCount')->findByPk($memberid);
		$company = $record->attributes;
		$company['favCount'] = $record->favCount;
		$services = $contact = array();
		foreach($record->contact as $value){
			$contact[] = $value->attributes;
			if(!isset($company['defaultContact']) || $value->zcc_default){
				$company['defaultContact'] = $value->attributes;
			}
		}
		foreach($record->services as $value){
			$services[] = $value->attributes;
			if($value->zcs_type==1 && (!isset($company['qqservice']) || $value->zcs_default)){
				$company['qqservice'] = $value->attributes;
			}
		}
		$company['services'] = $services;
		$company['contact'] = $contact;
		return $company;
	}
	
	/**
	 *根据二级域名生成公司Url
	 *return string
	 */
	public static function createCompanyUrl($sub_domain){
		if($sub_domain)
		return 'http://'.$sub_domain.'.'.preg_replace('/^http:\/\/www./i','',Yii::app()->homeUrl);
		return '#';
	}
	
	/**
	 *根据产品id生成公司链接，包含<a>标签和文字
	 *return string
	 */
	public static function createCompanyLinkByProid($productid, $options=array()){
		$memid = Product::model()->find('zp_id=\''.$productid.'\'')->zm_id;
		return self::model()->createCompanyLink($memid, $options);
	}
	
	/**
	 *根据会员id生成公司链接，包含<a>标签和文字
	 *return string
	 */
	public static function createCompanyLink($memberid, $options=array()){
		$criteria = new CDbCriteria();
		$criteria->select = 'zm_id,zc_sub_domain,zc_name';
		$criteria->compare('zm_id',$memberid);
		$model = Company::model()->find($criteria);
		$url = self::createCompanyUrl($model->zc_sub_domain);
		return CHtml::link($model->zc_name, $url, $options);
	}
	
	/**
	 * 经营模式
	 */
	public function getBusinessModel($type=null){
		if($type==null){
			return array(
					'个体经营'=>'个体经营',
					'网络经营'=>'网络经营',
			);
		}else{
			$level = $this->getBusinessModel();
			if(array_key_exists($type,$level))
				return $level[$type];
		}	
	}
	
	/**
	 * 经营模式
	 */
	public function getCustomize($type=null){
		if($type==null){
			return array(
					'1'=>'否',
					'2'=>'是',
			);
		}else{
			$level = $this->getCustomize();
			if(array_key_exists($type,$level))
				return $level[$type];
		}
	}
	
	/**
	 * 公司人数
	 */
	public function getLnsize($type=null){
		if($type==null){
			return array(
					'1-50'=>'1-50',
					'51-100'=>'51-100',
					'100-500'=>'500-2000',
					'2000以上'=>'2000以上',
			);
		}else{
			$level = $this->getLnsize();
			if(array_key_exists($type,$level))
				return $level[$type];
		}
	}
	
	/**
	 * 主要市场
	 */
	public function getMainMkt($type=null){
		if($type==null){
			return array(
					'大陆'=>'大陆',
					'港澳台'=>'港澳台',
					'东南亚'=>'东南亚',
					'欧美地区'=>'欧美地区',
					'拉丁美州'=>'拉丁美州',
			);
		}else{
			$level = $this->getMainMkt();
			if(array_key_exists($type,$level))
				return $level[$type];
		}
	}
	
	/**
	 * 年营业额
	 */
	public function getYearTurnover($type=null){
		if($type==null){
			return array(
					'3万'=>'3万',
					'5万'=>'5万',
					'10万'=>'10万',
					'50万'=>'50万',
					'100万'=>'100万',
			);
		}else{
			$level = $this->getMainMkt();
			if(array_key_exists($type,$level))
				return $level[$type];
		}
	}
	
	/**
	 * 企业类型
	 */
	public function getCmptype($type=null){
		if($type==null){
			return array(
					'民营企业'=>'民营企业',
					'台资企业'=>'台资企业',
					'香港企业'=>'香港企业',
					'外资企业'=>'外资企业',
					'中外合资'=>'中外合资',
			);
		}else{
			$level = $this->getMainMkt();
			if(array_key_exists($type,$level))
				return $level[$type];
		}
	}
	
	/**
	 * 注册资金
	 */
	public function getRegCapital($type=null){
		if($type==null){
			return array(
					'10万'=>'10万',
					'20万'=>'20万',
					'50万'=>'50万',
					'100万'=>'100万',
					'500万'=>'500万',
			);
		}else{
			$level = $this->getMainMkt();
			if(array_key_exists($type,$level))
				return $level[$type];
		}
	}
	
	/**
	 * 姓别 
	 */
	public function getSex($type=null){
		if($type==null){
			return array(
					'1'=>'先生',
					'2'=>'女士',
			);
		}else{
			$level = $this->getSex();
			if(array_key_exists($type,$level))
				return $level[$type];
		}
	}
	
	/**
	 * 网铺状态，用于查询
	 */
	public function getShopStatus($type=null){
		if($type==null){
			return array(
					'' =>'全部',
					'1'=>'资料审核',
					'2'=>'保证金审核',
					'3'=>'使用中',
					'4'=>'已禁止',
			);
		}else{
			$level = $this->getShopStatus();
			if(array_key_exists($type,$level))
				return $level[$type];
		}
	}
	
	public function afterFind(){
		//头部碎片
		$blockHead = Block::model()->findByAttributes(array('zm_id'=>$this->zm_id,'zbl_title'=>'block_head'));
		if(!empty($blockHead))
			$this->block_head = $blockHead->zbl_data;
		//右则碎片
		$blockRight = Block::model()->findByAttributes(array('zm_id'=>$this->zm_id,'zbl_title'=>'block_right'));
		if(!empty($blockRight))
			$this->block_right = $blockRight->zbl_data;
		//评论统计
		$this->comment = OrdComment::model()->getCmpAvg($this->zm_id);
		//多店铺的情况下生成二级域名，否则二级域名为网站域名
		if(F::setting("site_shop_type")==2){
			$this->domain = $this->createCompanyUrl($this->zc_sub_domain);
		}else{
			$this->domain = Yii::app()->homeUrl;
		}
		return true;
	}
	
}